package cn.skywalks.common.utils.context;

import cn.skywalks.common.utils.StringUtil;
import cn.skywalks.common.utils.pager.Pager;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lpeng on 2017/2/27.
 */
public class ContextUtil {

    private ContextUtil(){}

    /**
     * 将request放如当前线程
     * @param request
     */
    public static void setRequest(HttpServletRequest request){
        ThreadLocalUtil.set("threadHttpRequest", request);
    }

    /**
     * 获取request
     * @return
     */
    public static HttpServletRequest getRequest(){
        return (HttpServletRequest) ThreadLocalUtil.get("threadHttpRequest");
    }

    /**
     * 获取分页类，根据request中的参数
     * @return
     */
    public static Pager getPager(){
        HttpServletRequest request = ContextUtil.getRequest();
        Pager pager = null;
        if (null != request){
            String currentPage = request.getParameter(Pager.CURRENT_PAGE);
            String pageSize = request.getParameter(Pager.PAGESIZE);
            if (null == request || StringUtil.isEmpty(currentPage) || StringUtil.isEmpty(pageSize)){
                return null;
            }
            pager = new Pager();
            pager.setCurrentPage(StringUtil.isEmpty(currentPage) ? 1 : Integer.parseInt(currentPage));
            pager.setPageSize(StringUtil.isEmpty(pageSize) ? 10 : Integer.parseInt(pageSize));
        }
        return pager;
    }

    /**
     * 向request中放数据
     * @param key
     * @param value
     */
    public static void setRequestAttribute(String key, Object value) {
        HttpServletRequest request = (HttpServletRequest) ThreadLocalUtil.get("threadHttpRequest");
        request.setAttribute(key, value);
    }


    /**
     * 向request取数据
     * @param key
     */
    public static Object getRequestAttribute(String key) {
        HttpServletRequest request = (HttpServletRequest) ThreadLocalUtil.get("threadHttpRequest");
        return request.getAttribute(key);
    }

    /**
     * 获取分页总条数
     * @return
     */
    public static int getPagerTotal(){
        int total = 0;
        Pager pager = (Pager) ContextUtil.getRequestAttribute("pager");
        if (null != pager){
            total = pager.getTotal();
        }
        return total;
    }
}
